import getopt, sys, os, time
import message
import ConfigParser

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "f:s:h", ["help", "cfg-file=", 
            "cfg-section="])
    except getopt.GetoptError, err:
        # print help information and exit
        print str(err)
        _usage()
        sys.exit(2)

    # print opts
    cfg_file    = None
    cfg_section = None

    for p, v in opts:
        if p   in ('-f', '--cfg-file'):
            cfg_file = v
        elif p in ('-s', '--cfg-section'):
            cfg_section = v
        elif p in ('-h', '--help'):
            _usage()
            sys.exit()

    if cfg_file is not None:
        if os.path.exists(cfg_file):
            # read our config file
            config = ConfigParser.ConfigParser()
            config.read(cfg_file)

            try:
                values = config.items(cfg_section)
            except ConfigParser.NoSectionError, err:
                # supplied config section doesn't exists
                print "Error - " + str(err)
                sys.exit(2)

            cfg_values = {};

            for k, v in values:
                cfg_values[k] = v

            # ready for deamon
            _daemonize(cfg_values)

        else:
            print "Error - config file, " + cfg_file + " doesn't exists!"
            sys.exit(2)
    else:
        _usage()
        sys.exit()

def _daemonize(cfg):
    # load queue class
    class_queue =  __load_class__(cfg['module_queue_name'], 
        cfg['class_queue'])
    class_booth =  __load_class__(cfg['module_booth_name'], 
        cfg['class_booth'])

    # instantiate queues
    queue_in  = class_queue(cfg['var_file'], cfg['var_in'])
    queue_out = class_queue(cfg['var_file'], cfg['var_out'])

    # instantiate message processor
    # TODO: pass config here?
    booth = class_booth({})

    while True:
        print queue_in.queue_name + ' - fetch...'
        value = queue_in.dequeue();

        # TODO:
        #   convert string to a message object

        if value is not None:
            booth.process(value)

            print queue_in.queue_name + ' - sleep short...'
            # wait for a teeny, weeny while
            time.sleep(0.2)

        else:
            print queue_in.queue_name + ' - sleep long...'

            # wait
            time.sleep(5)

def __load_class__(module_name, class_name):
    m = __import__(module_name, fromlist=[class_name])

    try: 
        return getattr(m, class_name)
    except AttributeError, err:
        print 'Error - ' + str(err)
        sys.exit(2)

def _usage():
    print """Usage: tdlogic.py --cfg-file [path to file] --cfg-section [section name]
        --cfg-file, -f          : full path to where the config file is 
                                    located
        --cfg-section, -s       : what section of config file is to be used,
                                    see CONFIGURATION FORMAT.
        --help, -h              : displays this screen
    """

if __name__ == "__main__":
    main()
